package ch.bfh.cmdh.thinkerforge.weatherstation.model.humidity;

import java.io.IOException;
import java.net.UnknownHostException;

import ch.bfh.cmdh.thinkerforge.weatherstation.controller.WeatherStationController;
import ch.bfh.cmdh.thinkerforge.weatherstation.model.WeatherStationSensor;

import com.tinkerforge.AlreadyConnectedException;
import com.tinkerforge.BrickletHumidity;
import com.tinkerforge.BrickletHumidity.HumidityListener;
import com.tinkerforge.IPConnection;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;

public class HumiditySensor implements WeatherStationSensor {

    public static final String HUMIDITY_KEY = "humidity";

    private static final String HUMIDITY_SENSOR_UID = "dgf";
    private IPConnection ipConnection;
    private BrickletHumidity humidity;
    private WeatherStationController controller;

    public HumiditySensor(WeatherStationController controller){
        this.controller = controller;
        this.ipConnection = new IPConnection();
        humidity = new BrickletHumidity(HUMIDITY_SENSOR_UID, ipConnection);
        humidity.addHumidityListener(new HumiListener());
    }

    @Override
    public void connect() throws UnknownHostException, AlreadyConnectedException, IOException, TimeoutException,
            NotConnectedException {
        ipConnection.connect(WeatherStationController.HOST, WeatherStationController.PORT);
        humidity.setHumidityCallbackPeriod(WeatherStationController.CALLBACK_PERIOD);
    }

    @Override
    public void disconnect() throws NotConnectedException {
        ipConnection.disconnect();
    }

    private class HumiListener implements HumidityListener {

        @Override
        public void humidity(int humidity) {

            HumiditySensor.this.controller.updateGUI(HUMIDITY_KEY, humidity);

        }

    }
}
